package server

import (
	"blog/app/common"
	"blog/app/entity"
	"blog/app/model"
	"log"
	"strings"
	"strconv"
)

type ArticleServer struct {
}

func (*ArticleServer) Query(page *common.Page, params *entity.QueryParam) *[]entity.Article {
	//  先把标签对应的文章IDS查询出来
	log.Println("article server")
	if params.TagId > 0 {
		articleTag := model.ArticleTag{
			TagID: params.TagId,
		}
		params.ArticleIds = articleTag.GetArticleIdArr()
	}
	article := model.Article{}
	// 先查询总数
	total := article.Total(params)
	if total == 0 {
		return nil
	}
	page.SetToTal(total)
	articles := article.Query(page, params)
	return articles
}

func (*ArticleServer) Get(id uint64,ip string) *entity.Article{
	article := model.Article{
		ID:id,
	}
	a := article.Get()
	if ip != "" && a != nil{
		v := model.Visit{
			ArticleID:a.ID,
			IP:ip,
		}
		v.InsertOne()
	}
	return a
}

func (*ArticleServer) GetCreatedateStat() *[]entity.ArticleDate{
	article := model.Article{}
	return article.GetCreatedateStat()
}

func (*ArticleServer) Insert(param *entity.ArticleParam) bool{
	log.Println("article server")
	article := model.Article{
		Title:param.Title,
		Content:param.Content,
	}
	id,ok := article.InsertOne()
	if !ok{
		return ok
	}
	insertArticleTags(id,strings.TrimSpace(param.TagIds))
	return ok
}

func (*ArticleServer) Update(id uint64,param *entity.ArticleParam) bool {
	article := model.Article{
		ID:id,
		Title:param.Title,
		Content:param.Content,
	}
	ok := article.UpdateOne()
	if !ok{
		return ok
	}
	at := model.ArticleTag{
		ArticleID:id,
	}
	ok = at.DeleteOne()
	if !ok{
		return ok
	}
	insertArticleTags(id,strings.TrimSpace(param.TagIds))

	return ok
}

func (*ArticleServer) Delete(id uint64) bool{
	article := model.Article{
		ID:id,
	}
	ok := article.DeleteOne()
	if ok{
		at := model.ArticleTag{
			ArticleID:id,
		}
		at.DeleteOne()
	}
	return ok
}

func insertArticleTags(id uint64,tagIds string){
	tagIdArr := strings.Split(tagIds,",")
	var ids []interface{}
	status := true
	if tagIds != ""{
		for i := 0;i<len(tagIdArr);i++{
			ids = append(ids,id)
			v,err := strconv.Atoi(tagIdArr[i])
			if err != nil{
				status = false
				break
			}
			ids = append(ids,v)
		}
	}
	if status {
		articleTag := model.ArticleTag{}
		articleTag.BatchInsert(ids)
	}
}